/**
 * 
 */
package org.xnat.xnatfs.webdav;

import org.apache.log4j.Logger;
import org.xnat.xnatfs.util.PathUtils;

/**
 * @author blezek
 * 
 */
public class Project extends VirtualDirectory {
  final static Logger logger = Logger.getLogger ( Project.class );

  public Project ( XNATFS x, String path, String name, String url ) {
    super ( x, path, name, url );
    childKeys.add ( "ID" );
    childKeys.add ( "label" );
    childKeys.add ( "subjectid" );
    childNames.add ( "label" );
    elementURL = mURL + "subjects?format=json&columns=DEFAULT";
    verboseDirectoryName = "Subjects";
    extraChildren.add ( RESOURCES );
    if ( name.equals ( verboseDirectoryName ) ) {
      logger.debug ( "Directory is: " + PathUtils.tail ( PathUtils.dirname ( absolutePath ) ) );
      childKeys.add ( "sub_project_identifier_" + PathUtils.tail ( PathUtils.dirname ( absolutePath ) ).toLowerCase () );
    } else {
      childKeys.add ( "sub_project_identifier_" + name.toLowerCase () );
    }
  }

  @Override
  public VirtualResource child ( String childName ) {
    if ( xnatfs.useVerboseFolders () && !verboseDirectory ) {
      // this object is not the verbose folder, but we must create one.
      if ( childName.equals ( verboseDirectoryName ) ) {
        Project subjects = new Project ( xnatfs, absolutePath, verboseDirectoryName, mURL );
        subjects.setVerboseDirectory ( true );
        return subjects;
      }
    }
    if ( childName.equals ( RESOURCES ) ) {
      VirtualDirectory d = new Resources ( xnatfs, absolutePath, childName, mURL );
      d.setVerboseDirectory ( true );
      return d;
    }
    try {
      getElementList ();
    } catch ( Exception e ) {
      logger.error ( "Failed to cache element list", e );
    }
    if ( childMap.containsKey ( childName ) ) {
      logger.debug ( "child: create " + childName + " with name " + childMap.get ( childName ).name );
      // Look up in the cache
      VirtualResource subject = new Subject ( xnatfs, absolutePath, childMap.get ( childName ).name, mURL + "subjects/" + childMap.get ( childName ).id + "/" );
      return subject;
    }
    return null;
  }
}
